package encrypt

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
)

/*
	Asymmetric encryption requires the generation of a pair of keys rather than a key, so before encryption here you need to get a pair of keys, public and private, respectively
	Generate the public and private keys all at once
		Encryption: plaintext to the power E Mod N to output ciphertext
		Decryption: ciphertext to the power D Mod N outputs plaintext

		Encryption operations take a long time? Encryption is faster

		The data is encrypted and cannot be easily decrypted
*/

func GetRsaKey() (map[string]string, error) {
	// 生成 app rsa 密钥
	appRsaSecret, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}
	x509AppSecret := x509.MarshalPKCS1PrivateKey(appRsaSecret)
	appSecretBlock := pem.Block{
		Type:  privateKeyPrefix,
		Bytes: x509AppSecret,
	}
	appSecret := pem.EncodeToMemory(&appSecretBlock)

	appRsaKey := appRsaSecret.PublicKey
	x509PublicAppKey, err := x509.MarshalPKIXPublicKey(&appRsaKey)
	if err != nil {
		panic(err)
	}
	appKeyBlock := pem.Block{
		Type:  publicKeyPrefix,
		Bytes: x509PublicAppKey,
	}
	appKey := pem.EncodeToMemory(&appKeyBlock)

	// 生成 platform rsa 密钥
	platformRsaSecret, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}
	x509platformSecret := x509.MarshalPKCS1PrivateKey(platformRsaSecret)
	platformSecretBlock := pem.Block{
		Type:  privateKeyPrefix,
		Bytes: x509platformSecret,
	}
	platformSecret := pem.EncodeToMemory(&platformSecretBlock)

	platformRsaKey := platformRsaSecret.PublicKey
	x509PublicPlatformKey, err := x509.MarshalPKIXPublicKey(&platformRsaKey)
	if err != nil {
		panic(err)
	}
	platformKeyBlock := pem.Block{
		Type:  publicKeyPrefix,
		Bytes: x509PublicPlatformKey,
	}
	platformKey := pem.EncodeToMemory(&platformKeyBlock)

	rsaList := make(map[string]string)
	rsaList["AppKey"] = string(appKey)
	rsaList["AppSecret"] = string(appSecret)
	rsaList["PlatformKey"] = string(platformKey)
	rsaList["PlatformSecret"] = string(platformSecret)
	return rsaList, nil
}